<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Demo</title>
    <!-- 使用 jsDelivr 的其他镜像 -->
    <script src="https://fastly.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<input type="text" id="messageInput" placeholder="input content">
<button onclick="sendMessage()">send</button>
<div id="messages"></div>

<script>
    // 连接 WebSocket
    const socket = new SockJS('http://localhost:8080/ws');
    const stompClient = Stomp.over(socket);

    stompClient.connect({}, (frame) => {
        console.log('Connected: ' + frame);

        // 订阅 /topic/messages 以接收消息
        stompClient.subscribe('/topic/messages', (response) => {
            const message = JSON.parse(response.body).content;
            document.getElementById('messages').innerHTML += `<p>${message}</p>`;
        });
    });

    // 发送消息到服务端
    function sendMessage() {
        const message = document.getElementById('messageInput').value;
        stompClient.send("/app/chat", {}, JSON.stringify({ 'content': message }));
        document.getElementById('messageInput').value = '';
    }
</script>
</body>
</html>